<?php
/**
* @Author By Chris
*
* Created on 2011-8-2
*
*/

class TagModel extends Model
{
	
	
	public function getTag($aid = '')
	{
		if (empty($aid))//没有文档ID
		{
			return $this->field('tagname')->select();//返回所有tag标签
		}
		return $this->where("FIND_IN_SET('$aid',aid)")->field('tagname')->select();
	}
	
	public function getTagByName($tagName)
	{
		return $this->where(array('tagname'=>$tagName))->find();
	}
	
	//添加tag
	public function addTag($tagStr,$aid)
	{
		$tag = !empty($tagStr) ? explode(',', $tagStr) : array();
		$tag = array_filter(array_unique($tag));
		
		foreach ($tag as $tagName)
		{
			$result = $this->where(array('tagname'=>$tagName))->find();
			if ($result)
			{
				$sql = "UPDATE ".C('DB_PREFIX')."tag SET aid=concat(aid,'$aid,') where tagname = '$tagName'";
				$this->query($sql);
			}
			else
			{
				$aid.=',';
				$this->data(array('tagname'=>$tagName,'aid'=>$aid))->add();
			}
		}
		
	}
	
	//更新tag
	public function updateTag($tagStr,$aid)
	{
		$tag = !empty($tagStr) ? explode(',', $tagStr) : array();
		$get_tag = self::getTag($aid);
		$old_tag = array();
		foreach ($get_tag as $v)
		{
			$old_tag[] = $v['tagname'];
		}
		if (empty($old_tag))
		{
			$old_tag = array('');
		}
		$dif_tag = findArray(array_filter(array_unique($tag)),$old_tag);
		/*dump($dif_tag);
		exit();*/
		for($n = 0; $n < count($dif_tag); $n++)
		{
			$a = 0;
			for($j=0 ; $j<count($old_tag);$j++)
			{
				if($dif_tag[$n] == $old_tag[$j])
				{
					$this->query("UPDATE ".C('DB_PREFIX')."tag SET aid= REPLACE(aid,'$aid,','') WHERE tagname='".$dif_tag[$n]."' ");
					$this->query("DELETE FROM ".C('DB_PREFIX')."tag WHERE aid = '' ");
					break;
				}elseif($j == count($old_tag)-1){
					$result = $this->where(array('tagname'=>trim($dif_tag[$n])))->find();
//					$result = $this->db->once_fetch_array("SELECT tagname FROM ".C('DB_PREFIX')."tag WHERE tagname='".trim($dif_tag[$n])."' ");
					if(!$result)
					{
						$query="INSERT INTO ".C('DB_PREFIX')."tag (tagname,aid) VALUES('".$dif_tag[$n]."','$aid,')";
						$this->query($query);
					}else{
						$query="UPDATE ".C('DB_PREFIX')."tag SET aid=concat(aid,'$aid,') where tagname = '".$dif_tag[$n]."' ";
						$this->query($query);
					}
				}
			}
		}
	}
}
?>